package com.allwees.bs.c.module.payment.service.impl;

import com.allwees.bs.c.module.order.entity.OrderEntity;
import com.allwees.bs.c.module.payment.entity.PaymentLogEntity;
import com.allwees.bs.c.module.payment.repository.PaymentLogRepository;
import com.allwees.bs.c.module.payment.service.IPaymentLogService;
import com.allwees.support.payment.EPayMethod;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PaymentLogServiceImpl implements IPaymentLogService {

	@Autowired
	private PaymentLogRepository paymentLogRepository;

	@Override
	public PaymentLogEntity findByOrderUuid(String orderUuid) {
		return this.paymentLogRepository.findByOrderUuid(orderUuid);
	}

	@Override
	public PaymentLogEntity create(String paymentToken, int status, EPayMethod method, OrderEntity order) {
		PaymentLogEntity entity = paymentLogRepository.findByOrderUuid(order.getUuid());

		PaymentLogEntity paymentLog = new PaymentLogEntity().build(order, status, method);
		if(entity != null){
			paymentLog.setId(entity.getId());
		}
		paymentLog.setPaymentExpiresAt(order.getPaymentExpiredAt());
		paymentLog.setPaymentToken(paymentToken);
		return this.paymentLogRepository.save(paymentLog);
	}

	@Override
	public PaymentLogEntity payed(String orderUuid, String payId, String paymentNo) {
		PaymentLogEntity paymentLog = this.paymentLogRepository.findByOrderUuid(orderUuid);
		paymentLog.setStatus(PAYMENT_STATE_APPROVED);
		if(!StringUtils.isBlank(paymentNo)){
			paymentLog.setPaymentNumber(paymentNo);
		}
		if(!StringUtils.isBlank(payId)){
			paymentLog.setPayerId(payId);
		}
		return this.paymentLogRepository.save(paymentLog);
	}

	@Override
	public PaymentLogEntity cancel(String orderUuid) {
		PaymentLogEntity paymentLog = this.paymentLogRepository.findByOrderUuid(orderUuid);
		paymentLog.setStatus(PAYMENT_STATE_CANCEL);
		return this.paymentLogRepository.save(paymentLog);
	}
}
